package fr.neticar.webremoteclient.server;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

import fr.neticar.webremoteclient.client.ImagePropertyBean;

public class ImageManager {

	private static final long TIME_TO_LIVE = 30000;
	
	private Map<String, ImageContentBean> images;

	private Map<String, Long> timestamps;

	private Queue<ImagePropertyBean> queue;

	

	public ImageManager() {
		this.images = new HashMap<String, ImageContentBean>();
		this.timestamps = new HashMap<String, Long>();
		this.queue = new ConcurrentLinkedQueue<ImagePropertyBean>();
		TimerTask cleaningTask = new TimerTask() {
			@Override
			public void run() {
				List<String> deprecatedIds = new ArrayList<String>();
				long currentTimestamp = getTimestamp();
				for (String id : timestamps.keySet()) {
					Long aTimestamp = timestamps.get(id);
					if (currentTimestamp - aTimestamp >= TIME_TO_LIVE) {
						deprecatedIds.add(id);
					}
				}
				for (String id : deprecatedIds) {
					images.remove(id);
					timestamps.remove(id);
				}
			}
		};
		Timer timer = new Timer();
		timer.schedule(cleaningTask, TIME_TO_LIVE, TIME_TO_LIVE);
	}

	public void addImage(BufferedImage image, Rectangle destinationArea) {
		try {
			ImageContentBean contentBean = ImageUtils.convertToJPEG(image);
			String id = UUID.randomUUID().toString();
			ImagePropertyBean bean = new ImagePropertyBean(destinationArea.x, destinationArea.y, destinationArea.width,
					destinationArea.height, id);
			this.queue.add(bean);
			this.timestamps.put(id, getTimestamp());
			this.images.put(id, contentBean);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ImagePropertyBean getFirstBean() {
		return this.queue.poll();
	}

	public ImageContentBean getImage(String id) {
		ImageContentBean image = this.images.get(id);
		return image;
	}



	public boolean containsImage() {
		return queue.size() > 0;
	}

	private long getTimestamp() {
		return new Date().getTime();
	}

}
